﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using System.Globalization;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Services;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;
using NopSolutions.NopCommerce.BusinessLogic.Utils;

namespace NopSolutions.NopCommerce.Web.Modules
{
    public partial class CategoryFilterControl : BaseNopFrontendUserControl
    {
        private ICategoryService _categoryService;

        public CategoryFilterControl() {
            _categoryService = IoC.Resolve<ICategoryService>();
        }

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            Load += new EventHandler(CategoryFilterControl_Load);
            rptPriceRange.ItemDataBound += new RepeaterItemEventHandler(rptPriceRange_ItemDataBound);
        }

        void CategoryFilterControl_Load(object sender, EventArgs e) {
            if (!IsPostBack) {
                BindPriceRanges();
            }
        }

        #region Methods

        private void BindPriceRanges() {
            var priceRanges = new List<PriceRange>();

            var currentCategory = CurrentCategory;
            if (currentCategory != null && !string.IsNullOrWhiteSpace(currentCategory.PriceRanges)) {
                string[] rangeArray = CurrentCategory.PriceRanges.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string range in rangeArray) {
                    string[] _fromTo = range.Trim().Split(new char[] { '-' });

                    decimal? _from = null;
                    if (!String.IsNullOrEmpty(_fromTo[0]) && !String.IsNullOrEmpty(_fromTo[0].Trim())) {
                        _from = decimal.Parse(_fromTo[0].Trim(), new CultureInfo("en-US"));
                    }

                    decimal? _to = null;
                    if (!String.IsNullOrEmpty(_fromTo[1]) && !String.IsNullOrEmpty(_fromTo[1].Trim())) {
                        _to = decimal.Parse(_fromTo[1].Trim(), new CultureInfo("en-US"));
                    }

                    priceRanges.Add(new PriceRange() { From = _from, To = _to });
                }
            }

            rptPriceRange.DataSource = priceRanges;
            rptPriceRange.DataBind();
        }

        protected string GetPriceRangeString(decimal? From, decimal? To) {
            string result = string.Empty;
            if (!From.HasValue) {
                string toString = PriceHelper.FormatPrice(To.Value, true, false);
                result = string.Format(GetLocaleResourceString("Common.PriceRangeFilter.Under"), toString);
            }
            else if (!To.HasValue) {
                string fromString = PriceHelper.FormatPrice(From.Value, true, false);
                result = string.Format(GetLocaleResourceString("Common.PriceRangeFilter.Over"), fromString);
            }
            else {
                string fromString = PriceHelper.FormatPrice(From.Value, true, false);
                string toString = PriceHelper.FormatPrice(To.Value, true, false);
                result = string.Format("{0} - {1}", fromString, toString);
            }
            return result;
        }

        #endregion

        #region Events

        void rptPriceRange_ItemDataBound(object sender, RepeaterItemEventArgs e) {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
                var priceRange = e.Item.DataItem as PriceRange;
                if (priceRange != null) {
                    var lnkPriceRange = e.Item.FindControl("lnkPriceRange") as HyperLink;

                    // text
                    lnkPriceRange.Text = GetPriceRangeString(priceRange.From, priceRange.To);

                    // class
                    string cssClass = "inactive";
                    string qs = Request.QueryString["Price"];

                    if (!string.IsNullOrWhiteSpace(qs)) {
                        string fromQs = qs.Split(new char[] { '-' })[0];
                        string toQs = qs.Split(new char[] { '-' })[1];

                        if (
                            (
                                (!priceRange.From.HasValue && string.IsNullOrWhiteSpace(fromQs)) &&
                                (priceRange.To.HasValue && !string.IsNullOrWhiteSpace(toQs) && priceRange.To.Value.ToString(new CultureInfo("en-US")).Equals(toQs))
                            ) ||
                            (
                                (priceRange.From.HasValue && !string.IsNullOrWhiteSpace(fromQs) && priceRange.From.Value.ToString(new CultureInfo("en-US")).Equals(fromQs)) &&
                                (priceRange.To.HasValue && !string.IsNullOrWhiteSpace(toQs) && priceRange.To.Value.ToString(new CultureInfo("en-US")).Equals(toQs))
                            ) ||
                            (
                                (priceRange.From.HasValue && !string.IsNullOrWhiteSpace(fromQs) && priceRange.From.Value.ToString(new CultureInfo("en-US")).Equals(fromQs)) &&
                                (!priceRange.To.HasValue && string.IsNullOrWhiteSpace(toQs)))
                        ) {
                            cssClass = "active";
                        }
                    }

                    lnkPriceRange.CssClass = cssClass;

                    // url
                    string fromQuery = string.Empty;
                    if (priceRange.From.HasValue) {
                        fromQuery = priceRange.From.Value.ToString(new CultureInfo("en-US"));
                    }

                    string toQuery = string.Empty;
                    if (priceRange.To.HasValue) {
                        toQuery = priceRange.To.Value.ToString(new CultureInfo("en-US"));
                    }


                    var url = CommonHelper.ModifyQueryString(CommonHelper.GetThisPageUrl(true), "Price=" + fromQuery + "-" + toQuery, null);
                    lnkPriceRange.NavigateUrl = url;
                }
            }
        }

        #endregion

        #region Properties

        private int CategoryId {
            get { return CommonHelper.RouteStringInt("categoryId"); }
        }

        private Category CurrentCategory {
            get { return _categoryService.GetCategoryById(CategoryId); }
        }

        #endregion
    }
}